<template>
	<div>
		<div ref="el" class="whitespace-pre-wrap" :class="{ isEllipsis }">
			{{ text }}
		</div>
		<div
			v-if="hasEllipsis"
			@click.stop="onCollapse"
			class="mt-1 text-sm text-primary app-text-react"
			:class="actionClass">
			{{ $t(`action.${show ? 'collapse' : 'expand'}`) }}
		</div>
	</div>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref, watch } from 'vue'

const props = defineProps({
	lineClamp: {
		type: Number,
		default: 3
	},
	actionClass: {
		type: String,
		default: ''
	},
	text: {
		type: String,
		default: ''
	}
})

const emits = defineEmits(['collapse'])

const el = ref<HTMLElement | null>(null)

const hasEllipsis = ref(false)

const show = ref(false)

const isEllipsis = computed(() => !show.value)

const onCollapse = () => {
	show.value = !show.value
	emits('collapse')
}

onMounted(() => {
	if (el.value) {
		hasEllipsis.value = el.value.scrollHeight - el.value.offsetHeight > 5
	}
})

watch(
	() => props.text,
	() => {
		setTimeout(() => {
			if (el.value) {
				hasEllipsis.value = el.value.scrollHeight - el.value.offsetHeight > 5
			}
		})
	}
)
</script>

<style lang="scss" scoped>
.isEllipsis {
	overflow: hidden;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: v-bind(lineClamp);
}
</style>
